package net.wicp.tams.common.thread.event;

import java.lang.reflect.Method;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.common.eventbus.AllowConcurrentEvents;
import com.google.common.eventbus.Subscribe;

import net.wicp.tams.common.apiext.ReflectAssist;
import net.wicp.tams.common.constant.ObjectElement;

/**
 * 事件监听类， 通过反射调用传入event中的方法
 * 
 * @author fengyanbin
 */
public class EventListener {
	private final static Logger logger = LoggerFactory.getLogger(EventListener.class);

	@Subscribe
	@AllowConcurrentEvents
	public void listen(Event event) throws Exception {
		if (null == event) {
			logger.warn("EventListener.listen() event is null, do nothing");
			return;
		}
		// 目标方法参数列表
		Object[] args = event.getArgs();
		// 目标方法参数类型列表
		@SuppressWarnings("rawtypes")
		Class[] parameterTypes = event.getClazzs();

		if (null == parameterTypes) {
			if (null != args && args.length > 0) {
				parameterTypes = new Class[args.length];
				for (int i = 0; i < args.length; i++) {
					parameterTypes[i] = args[i].getClass();
				}
			}
		}
		// 取bean的方法对象
		Method method = event.getBean().getClass().getDeclaredMethod(event.getMethodName(), parameterTypes);
		method.setAccessible(true);
		// 调用目标方法
		method.invoke(event.getBean(), args);
	}

	@Subscribe
	@AllowConcurrentEvents
	public void listenStatic(Map<ObjectElement, Object> inputobj) throws Exception {
		String classNamestr = String.valueOf(inputobj.get(ObjectElement.className));
		String methodNamestr = String.valueOf(inputobj.get(ObjectElement.methodName));
		Object[] paramsobjs = inputobj.get(ObjectElement.params)==null?null:(Object[]) inputobj.get(ObjectElement.params);
		ReflectAssist.invokeStaticMothed(classNamestr, methodNamestr, paramsobjs);
	}
}
